// FR1: 前端 i18n 国际化服务工具类。用于根据页面语言设置提供多语言翻译能力。
// FR1: 本文件为纯 TypeScript 工具类，不包含 JSX 语法，故采用 .ts 格式，符合项目工具类文件规范。
//
// Copyright Thoughtworks, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Epic-10 优化：实现智能的按页面和语言加载策略
// 1. 只加载当前页面需要的翻译
// 2. 只加载当前语言的翻译
// 3. 智能缓存，避免重复加载
// 4. 性能优化，减少网络请求

interface BackendTranslations {
    'zh-CN'?: { [key: string]: string };
    'en'?: { [key: string]: string };
}

interface PageTranslations {
    [page: string]: BackendTranslations;
}

interface LoadingState {
    [page: string]: Promise<void> | undefined;
}

class I18nService {
    private translations: any = {};
    private pageTranslations: PageTranslations = {}; // 按页面缓存翻译
    private isInitialized: boolean = false;
    private initializationPromise: Promise<void> | null = null;
    private useBackend: boolean = true; // 默认启用后端模式
    private backendUrl: string = '/go/api/i18n';

    // Epic-10 新增：智能加载状态管理
    private loadingStates: LoadingState = {}; // 防止重复加载
    private currentPage: string | null = null; // 当前页面标识
    private currentLocale: string | null = null; // 当前语言标识

    constructor() {
        // 自动初始化
        this.initializeWhenReady();
    }

    private initializeWhenReady() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    private async initialize() {
        if (this.isInitialized || this.initializationPromise) {
            return;
        }

        this.initializationPromise = this.loadLocale();
        await this.initializationPromise;
        this.isInitialized = true;
    }

    private async loadLocale() {
        const currentLocale = this.getCurrentLocale();
        this.currentLocale = currentLocale;

        if (this.useBackend) {
            try {
                // Epic-10 优化：不再一次性加载所有翻译，而是按需加载
                console.log('Initializing i18n service with locale:', currentLocale);
                // 初始化时不加载任何翻译，等待页面调用时再加载
                this.translations = {
                    'zh-CN': {},
                    'en': {}
                };
            } catch (error) {
                console.warn('Failed to initialize i18n service, falling back to empty translations:', error);
                this.translations = {
                    'zh-CN': {},
                    'en': {}
                };
            }
        } else {
            this.translations = {
                'zh-CN': {},
                'en': {}
            };
        }
    }

    /**
     * Epic-10 优化：智能按页面和语言加载翻译
     * 1. 只加载指定页面的翻译
     * 2. 只加载当前语言的翻译
     * 3. 智能缓存，避免重复加载
     */
    async loadFromBackendforPage(locale: string, page: string): Promise<void> {
        // 检查是否已经在加载中
        if (this.loadingStates[page]) {
            console.log(`Translations for page ${page} are already loading, waiting...`);
            return this.loadingStates[page]!;
        }

        // 检查是否已经加载过
        if (this.pageTranslations[page]) {
            console.log(`Translations for page ${page} already loaded, using cache`);
            return;
        }

        // 创建加载Promise
        const loadPromise = this._loadFromBackendforPage(locale, page);
        this.loadingStates[page] = loadPromise;

        try {
            await loadPromise;
            console.log(`Successfully loaded translations for page ${page}`);
        } finally {
            // 清理加载状态
            delete this.loadingStates[page];
        }
    }

    private async _loadFromBackendforPage(locale: string, page: string): Promise<void> {
        try {
            const url = new URL(this.backendUrl, window.location.origin);
            url.searchParams.set('locale', locale);
            url.searchParams.set('page', page);

            console.log(`Loading translations for page: ${page}, locale: ${locale}`);

            const response = await fetch(url.toString(), {
                method: 'GET',
                headers: {
                    'Accept': 'application/vnd.go.cd.v1+json',
                    'Content-Type': 'application/json',
                },
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data: BackendTranslations = await response.json();

            // Epic-10 优化：只缓存当前语言的翻译，节省内存
            const normalizedData: BackendTranslations = {};

            if (locale === 'zh') {
                normalizedData['zh-CN'] = data['zh-CN'] || {};
                // 不缓存英文翻译，节省内存
            } else if (locale === 'en') {
                normalizedData['en'] = data['en'] || {};
                // 不缓存中文翻译，节省内存
            }

            // 按页面缓存翻译
            this.pageTranslations[page] = normalizedData;

            console.log(`Successfully loaded translations for page ${page} and locale ${locale}:`, normalizedData);
        } catch (error) {
            console.error(`Error loading translations for page ${page} and locale ${locale}:`, error);
            throw error;
        }
    }

    /**
     * Epic-10 优化：智能获取页面翻译
     * 自动检测当前页面并加载对应翻译
     */
    async getPageTranslations(page: string): Promise<BackendTranslations> {
        // 如果页面翻译未加载，自动加载
        if (!this.pageTranslations[page]) {
            const currentLocale = this.getCurrentLocale();
            await this.loadFromBackendforPage(currentLocale, page);
        }
        return this.pageTranslations[page];
    }

    /**
     * Epic-10 优化：设置当前页面上下文
     * 用于自动加载页面翻译
     */
    setCurrentPage(page: string): void {
        if (this.currentPage !== page) {
            this.currentPage = page;
            console.log(`Current page set to: ${page}`);

            // 自动预加载当前页面的翻译
            this.preloadPageTranslations(page);
        }
    }

    /**
     * Epic-10 新增：预加载页面翻译
     * 在页面切换时自动调用
     */
    private async preloadPageTranslations(page: string): Promise<void> {
        try {
            const currentLocale = this.getCurrentLocale();
            await this.loadFromBackendforPage(currentLocale, page);
        } catch (error) {
            console.warn(`Failed to preload translations for page ${page}:`, error);
        }
    }

    /**
     * Epic-10 优化：按页面翻译文本（同步版本）
     * 现在只使用对应 locale 的翻译，提升性能
     */
    tSyncForPage(key: string, page: string): string {
        const pageTranslations = this.pageTranslations[page];
        if (!pageTranslations) {
            console.warn(`Translations for page ${page} not loaded yet, key: ${key}`);
            return key;
        }

        const currentLocale = this.getCurrentLocale();
        const localeKey = currentLocale === 'zh' ? 'zh-CN' : 'en';

        // Epic-10 优化：只查找对应 locale 的翻译，避免不必要的查找
        const translation = pageTranslations[localeKey]?.[key];
        if (translation) {
            return translation;
        }

        // 如果找不到翻译，返回键名
        console.warn(`Translation not found for key '${key}' in page '${page}' and locale '${currentLocale}'`);
        return key;
    }

    /**
     * Epic-10 新增：批量预加载多个页面的翻译
     * 用于需要同时显示多个页面内容的场景
     */
    async preloadMultiplePages(pages: string[]): Promise<void> {
        const currentLocale = this.getCurrentLocale();
        const loadPromises = pages.map(page => this.loadFromBackendforPage(currentLocale, page));

        try {
            await Promise.all(loadPromises);
            console.log(`Successfully preloaded translations for pages: ${pages.join(', ')}`);
        } catch (error) {
            console.warn('Failed to preload some page translations:', error);
        }
    }

    /**
     * Epic-10 新增：清理页面翻译缓存
     * 用于内存管理和强制刷新
     */
    clearPageCache(page?: string): void {
        if (page) {
            delete this.pageTranslations[page];
            console.log(`Cleared cache for page: ${page}`);
        } else {
            this.pageTranslations = {};
            console.log('Cleared all page translation caches');
        }
    }

    /**
     * Epic-10 新增：获取缓存状态信息
     * 用于调试和监控
     */
    getCacheStatus(): { cachedPages: string[], loadingPages: string[], currentPage: string | null, currentLocale: string | null } {
        return {
            cachedPages: Object.keys(this.pageTranslations),
            loadingPages: Object.keys(this.loadingStates).filter(page => this.loadingStates[page] !== undefined),
            currentPage: this.currentPage,
            currentLocale: this.currentLocale
        };
    }

    public enableBackendMode(): void {
        this.useBackend = true;
        console.log('Backend mode enabled');
    }

    public disableBackendMode(): void {
        this.useBackend = false;
        console.log('Backend mode disabled');
    }

    public setBackendUrl(url: string): void {
        this.backendUrl = url;
        console.log('Backend URL set to:', url);
    }

    public async reloadTranslations(): Promise<void> {
        this.isInitialized = false;
        this.initializationPromise = null;
        this.clearPageCache(); // 清理所有页面缓存
        await this.initialize();
    }

    // 异步获取翻译（用于动态加载的文本）
    async t(key: string): Promise<string> {
        await this.initialize();
        const currentLocale = this.getCurrentLocale();
        const localeKey = currentLocale === 'zh' ? 'zh-CN' : 'en';

        // 检查翻译是否存在
        if (this.translations && this.translations[localeKey] && this.translations[localeKey][key]) {
            return this.translations[localeKey][key];
        }
        // 回退到键名
        return key;
    }

    // 加载页面特定的翻译
    public async loadPageTranslations(pageName: string): Promise<void> {
        try {
            const currentLocale = this.getCurrentLocale();
            await this.loadFromBackendforPage(currentLocale, pageName);
            console.log(`Successfully loaded ${pageName} page translations`);
        } catch (error) {
            console.warn(`Failed to load ${pageName} page translations:`, error);
        }
    }

    // 同步获取翻译（推荐用于静态文本）
    tSync(key: string): string {
        const currentLocale = this.getCurrentLocale();
        const localeKey = currentLocale === 'zh' ? 'zh-CN' : 'en';

        // 检查翻译是否存在
        if (this.translations && this.translations[localeKey] && this.translations[localeKey][key]) {
            return this.translations[localeKey][key];
        }

        // 回退到键名
        return key;
    }

    private getCurrentLocale(): string {
        // 从页面元素获取当前语言设置
        const localeElement = document.querySelector('[data-locale]') as HTMLElement;
        if (localeElement) {
            const locale = localeElement.dataset.locale || 'en';
            // 将 zh-CN 转换为 zh，因为后端只接受 zh 和 en
            return locale === 'zh-CN' ? 'zh' : locale;
        }

        // 从 URL 参数获取
        const urlParams = new URLSearchParams(window.location.search);
        const localeParam = urlParams.get('locale');
        if (localeParam && ['zh', 'en', 'zh-CN'].includes(localeParam)) {
            // 将 zh-CN 转换为 zh
            return localeParam === 'zh-CN' ? 'zh' : localeParam;
        }

        // 默认返回英文
        return 'en';
    }
}

export const i18n = new I18nService();
